﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web.Mvc;
using LuKou.Shopspace.Domains;
using LuKou.Web.BLL;
using LuKou.Web.BLL.Extensions;
using LuKou.Web.BLL.Service;
using LuKou.Web.Controllers.Base;
using LuKou.Web.Core;
using LuKou.Web.Form;
using LuKou.Web.Helper;
using LuKou.Web.UserAuth;
using LuKou.Web.ViewModel;
using LuKou.Member;
using System.Linq;
using LuKou.Shopspace;

namespace LuKou.Web.Controllers.Website
{
    /// <summary>
    /// 厂商后台相关功能控制器
    /// </summary>
    [WebAuthorize(UserType = WebUserType.Seller | WebUserType.Agents | WebUserType.System)]
    public class SellerController : WebBaseController
    {
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        #region 我的账户

        [HttpGet]
        public ActionResult UserInfo()
        {
            long ID = this.UserSession.UserID;
            LuKou.Member.Domains.User user = UserService.GetUserInfoById(ID);
            if (null == user)
            {
                return this.RedirectIndex();
            }
            return View(new UserEditInfo()
            {
                Email = user.Email,
                ID = ID,
                Name = user.Name,
                UserSex = user.Sex,
                UserType = user.UserType
            });
        }

        [HttpPost]
        public ActionResult UserInfo(UserEditInfo model)
        {
            if (!ModelState.IsValid
                || null == Session["VerifyCode"]
                || string.Compare(model.ValidateCode, Session["VerifyCode"].ToString(), StringComparison.CurrentCultureIgnoreCase) != 0)
            {
                if (!string.IsNullOrEmpty(model.ValidateCode))
                {
                    ModelState.AddModelError("ValIDateCode", "请输入正确的验证码。");
                }
                return View(model);
            }

            try
            {
                UserService.ModifyUser(new LuKou.Member.Domains.User()
                {
                    Email = model.Email,
                    ID = model.ID,
                    Name = model.Name,
                    Sex = model.UserSex
                });
            }
            catch (Exception)
            {
                ModelState.AddModelError("ErrTips", "修改资料失败。");
                return View(model);
            }

            ModelState.AddModelError("ErrTips", "修改资料成功。");
            return View(model);
        }

        [HttpGet]
        public ActionResult ChangePassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ChangePassword(UserPwdInfo model)
        {
            if (!ModelState.IsValid
                || string.Compare(model.PassWord, model.RePassWord, StringComparison.CurrentCulture) != 0)
            {
                if (!string.IsNullOrEmpty(model.RePassWord))
                {
                    ModelState.AddModelError("RePassWord", "两次密码不一致。");
                }
                return View("ChangePassword");
            }
            try
            {
                UserService.ChangePassword(model.ID, model.OldPassWord, model.RePassWord);
            }
            catch (Exception)
            {
                ModelState.AddModelError("ErrTips", "修改密码失败。");
                return View("ChangePassword");
            }
            ModelState.AddModelError("ErrTips", "修改密码成功。");
            return View("ChangePassword");
        }

        #endregion

        #region 我是厂家

        public ActionResult ProductList(int? pageindex, int? pagesize)
        {
            int pageIndex = pageindex ?? 1;
            int pageSize = pagesize ?? 10;
            int count = Convert.ToInt32(this.UserSession.GetShop().GetGoodsCount());

            PagedList<Goods> result = new PagedList<Goods>(
                this.UserSession.GetShop().GetGoodsList(pageIndex, pageSize), pageIndex, pageSize, count);
            return View(result);
        }

        [HttpGet]
        public ActionResult AddGoods()
        {
            if (this.UserSession.GetShop() == null)
            {
                throw new Exception("用户店铺不存在");
            }

            long parentId;
            if (!long.TryParse(ConfigurationManager.AppSettings["CategoryId"], out parentId))
            {
                parentId = 0L;
            }

            //商品分类
            List<Category> categoryList = CategoryService.GetCategoryList(parentId);
            List<SelectListItem> cateOptins = new List<SelectListItem>();
            foreach (var cate in categoryList)
            {
                cateOptins.Add(new SelectListItem() { Text = cate.Name, Value = cate.ID.ToString() });
            }
            ViewData["CategoryOptions"] = cateOptins;

            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AddGoods(GoodsForm goods)
        {
            if (!ModelState.IsValid)
            {
                long parentId;
                if (!long.TryParse(ConfigurationManager.AppSettings["CategoryId"], out parentId))
                {
                    parentId = 0L;
                }
                //商品分类
                List<Category> categoryList = CategoryService.GetCategoryList(parentId);
                List<SelectListItem> cateOptins = new List<SelectListItem>();
                foreach (var cate in categoryList)
                {
                    cateOptins.Add(new SelectListItem() { Text = cate.Name, Value = cate.ID.ToString() });
                }
                ViewData["CategoryOptions"] = cateOptins;

                return View("AddGoods");
            }

            //添加数据到数据库
            Goods dbGoods = new Goods()
            {
                ShopID = this.UserSession.GetShop().ID,
                CategoryID = goods.CategoryID,
                Description = goods.Description,
                IsRecommend = goods.Recommended,
                Tag = goods.Tags,
                Title = goods.Name,
                GoodsState = goods.IsShow ? 0 : 1
            };

            //添加属性数据
            dbGoods.Attribs = new List<GoodsAttrib>();
            dbGoods.DefAttribs = new List<GoodsDefAttrib>();
            if (goods.TbAttr != null && goods.TbAttr.Count > 0)
            {
                foreach (var item in goods.TbAttr)
                {
                    if (item == null || item.Vid == null) continue;
                    foreach (var attr in item.Vid)
                    {
                        if (attr.IsInteger())
                        {
                            dbGoods.Attribs.Add(new GoodsAttrib()
                            {
                                CategoryID = goods.CategoryID,
                                Pid = item.Pid,
                                Vid = attr.ToInt32()
                            });
                        }
                        else if (!attr.IsNullOrEmpty() && attr.Trim() != "-1")
                        {
                            dbGoods.DefAttribs.Add(new GoodsDefAttrib()
                            {
                                CategoryID = goods.CategoryID,
                                CharValue = attr,
                                Pid = item.Pid
                            });
                        }
                    }
                }
            }

            //SUK数据
            //dbGoods.SUKs = new List<GoodsSUK>();

            //添加到数据库
            long gid = GoodsService.AddGoods(dbGoods);

            //添加图片信息
            if (goods.MajorImages != null)
            {
                foreach (var img in goods.MajorImages)
                {
                    GoodsService.AddGoodsImage(gid, img, true);
                }
            }

            if (goods.Images != null)
            {
                foreach (var img in goods.Images)
                {
                    GoodsService.AddGoodsImage(gid, img, false);
                }
            }

            return RedirectToAction("ProductList");
        }

        [HttpGet]
        public ActionResult EditGoods(int id)
        {
            #region 页面内容
            if (this.UserSession.GetShop() == null)
            {
                throw new Exception("用户店铺不存在");
            }

            long parentId;
            if (!long.TryParse(ConfigurationManager.AppSettings["CategoryId"], out parentId))
            {
                parentId = 0L;
            }

            //商品分类
            List<Category> categoryList = CategoryService.GetCategoryList(parentId);
            List<SelectListItem> cateOptins = new List<SelectListItem>();
            foreach (var cate in categoryList)
            {
                cateOptins.Add(new SelectListItem() { Text = cate.Name, Value = cate.ID.ToString() });
            }
            ViewData["CategoryOptions"] = cateOptins;
            #endregion

            //从数据库获取数据
            Goods dbGoods = GoodsService.GetGoodsDetail(id);
            if (dbGoods == null || dbGoods.ShopID != UserSession.GetShop().ID)
            {
                throw new Exception("商品信息不存在");
            }

            GoodsForm goods = new GoodsForm()
            {
                GoodsID = dbGoods.ID,
                Brand = dbGoods.Tag,
                CategoryID = dbGoods.CategoryID,
                Description = dbGoods.Description,
                DownLevel = (int)dbGoods.AgentsGradeID,
                IsShow = dbGoods.GoodsState == 1,
                Name = dbGoods.Title,
                Price = (float)dbGoods.Price,
                Recommended = dbGoods.IsRecommend,
                Tags = dbGoods.Tag,
            };

            //商品的主图片
            ViewData["majorImages"] = dbGoods.GetMajorImages();
            //商品的图片
            ViewData["images"] = dbGoods.GetImages();

            return View(goods);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditGoods(int id, GoodsForm goods)
        {
            //从数据库获取数据
            goods.GoodsID = id;
            Goods dbGoods = GoodsService.GetGoodsDetail(id);
            if (dbGoods == null || dbGoods.ShopID != UserSession.GetShop().ID)
            {
                throw new Exception("商品信息不存在");
            }

            //先保存图片信息
            if (goods.MajorImages != null)
            {
                GoodsService.DeleteGoodsImage(id, true);
                foreach (var img in goods.MajorImages)
                {
                    GoodsService.AddGoodsImage(id, img, true);
                }
            }

            if (goods.Images != null)
            {
                GoodsService.DeleteGoodsImage(id, false);
                foreach (var img in goods.Images)
                {
                    GoodsService.AddGoodsImage(id, img, false);
                }
            }

            if (!ModelState.IsValid)
            {
                long parentId;
                if (!long.TryParse(ConfigurationManager.AppSettings["CategoryId"], out parentId))
                {
                    parentId = 0L;
                }
                //商品分类
                List<Category> categoryList = CategoryService.GetCategoryList(parentId);
                List<SelectListItem> cateOptins = new List<SelectListItem>();
                foreach (var cate in categoryList)
                {
                    cateOptins.Add(new SelectListItem() { Text = cate.Name, Value = cate.ID.ToString() });
                }
                ViewData["CategoryOptions"] = cateOptins;

                //商品的主图片
                ViewData["majorImages"] = dbGoods.GetMajorImages();
                //商品的图片
                ViewData["images"] = dbGoods.GetImages();

                return View(goods);
            }

            //更新数据
            dbGoods.CategoryID = goods.CategoryID;
            dbGoods.Description = goods.Description;
            dbGoods.IsRecommend = goods.Recommended;
            dbGoods.Tag = goods.Tags;
            dbGoods.Title = goods.Name;
            dbGoods.GoodsState = goods.IsShow ? 0 : 1;
            dbGoods.Amount = goods.Stock;

            //更新属性数据
            dbGoods.Attribs = new List<GoodsAttrib>();
            dbGoods.DefAttribs = new List<GoodsDefAttrib>();
            if (goods.TbAttr != null && goods.TbAttr.Count > 0)
            {
                foreach (var item in goods.TbAttr)
                {
                    if (item == null || item.Vid == null) continue;
                    foreach (var attr in item.Vid)
                    {
                        if (attr.IsInteger())
                        {
                            dbGoods.Attribs.Add(new GoodsAttrib()
                            {
                                CategoryID = goods.CategoryID,
                                Pid = item.Pid,
                                Vid = attr.ToInt32()
                            });
                        }
                        else if (!attr.IsNullOrEmpty() && attr.Trim() != "-1")
                        {
                            dbGoods.DefAttribs.Add(new GoodsDefAttrib()
                            {
                                CategoryID = goods.CategoryID,
                                CharValue = attr,
                                Pid = item.Pid
                            });
                        }
                    }
                }
            }

            //更新SUK数据
            dbGoods.SKUs = new List<GoodsSKU>();
            if (goods.GoodsSku != null && goods.GoodsSku.Count > 0)
            {
                foreach (var sku in goods.GoodsSku)
                {
                    dbGoods.SKUs.Add(new GoodsSKU(){
                        Amount=sku.Amount,
                        Price = sku.Price,
                        OuterNum = sku.OuterNum,
                        SKUProps = sku.GetSkuProps()
                    });
                }
            }

            GoodsService.EditGoods(dbGoods);
            return RedirectToAction("ProductList");
        }

        [HttpPost]
        public ActionResult SelDelete(int[] chkSingle)
        {
            if (chkSingle.Length > 0)
            {
                GoodsService.Delete(chkSingle);
            }
            return RedirectToAction("ProductList");
        }

        [HttpGet]
        public ActionResult Del(int id)
        {
            if (id > 0)
            {
                GoodsService.Delete(new int[] { id });
            }
            return RedirectToAction("ProductList");
        }

        //店铺信息
        [HttpGet]
        public ActionResult Shop()
        {
            Shop shopInfo = this.UserSession.GetShop();
            if (null == shopInfo)
            {
                this.RedirectIndex();
            }
            ShopForm shop = new ShopForm()
            {
                ID = shopInfo.ID,
                FullName = shopInfo.FullName,
                SummaryName = shopInfo.SummaryName,
                SecondlevelDomain = shopInfo.SecondlevelDomain,
                QQ = shopInfo.QQ,
                WangWang = shopInfo.WangWang,
                QQGroup = shopInfo.QQGroup,
                Address = shopInfo.Address,
                Postcode = shopInfo.Postcode,
                Phone = shopInfo.Phone,
                BannerUrl = shopInfo.BannerURL,
                Description = shopInfo.Description,
                Bulletin = shopInfo.Bulletin
            };
            return View(shop);
        }

        //店铺信息
        [HttpPost]
        public ActionResult Shop(ShopForm shopInfo)
        {
            if (!ModelState.IsValid)
            {
                return View("Shop");
            }
            try
            {
                Shop shop = new Shop()
                {
                    ID = shopInfo.ID,
                    FullName = shopInfo.FullName,
                    SummaryName = shopInfo.SummaryName,
                    SecondlevelDomain = shopInfo.SecondlevelDomain,
                    QQ = shopInfo.QQ,
                    WangWang = shopInfo.WangWang,
                    QQGroup = shopInfo.QQGroup,
                    Address = shopInfo.Address,
                    Postcode = shopInfo.Postcode,
                    Phone = shopInfo.Phone,
                    BannerURL = shopInfo.BannerUrl,
                    Description = shopInfo.Description,
                    Bulletin = shopInfo.Bulletin
                };
                ShopService.UpdateShopInfo(shop, this.UserSession.UserID);
                return RedirectToAction("Shop");
            }
            catch (Exception e)
            {
                ModelState.AddModelError("Error", e.Message);
            }
            return View("Shop");
        }

        //关注会员
        [HttpGet]
        public ActionResult ConcernUser()
        {
            //GoodsAccessRecord  
            //LuKou.Shopspace.EGoodsAccessType
            //GoodsAccessRecordQueryParam
            //GoodsSvr.GetGoodsAccessRecordList 
            return View();
        }
        //会员管理
        [HttpGet]
        public ActionResult ShopMember(int? pageindex, int? pagesize)
        {
            //VendorShopMember  
            return View(ShopService.GetVendorShopMemberList(pageindex ?? 1, pagesize ?? 10));
        }

        //店铺动态
        [HttpGet]
        public ActionResult ShopNotice(int? pageindex, int? pagesize)
        {
            //ShopArticle  
            Shop shopInfo = this.UserSession.GetShop();
            if (null == shopInfo)
            {
                throw new Exception("用户店铺不存在");
            }
            return View(ShopArticleService.GetShopArticleList(pageindex ?? 1, pagesize ?? 10, shopInfo.ID));
        }

        [HttpPost]
        public ActionResult ShopNotice(FormCollection form)
        {
            //ShopArticle 
            string content = form["Content"];
            string title = form["Title"];

            if (content.IsNullOrEmptyOrWhiteSpace())
            {
                ModelState.AddModelError("content", "内容为空。");
            }

            if (title.IsNullOrEmptyOrWhiteSpace())
            {
                ModelState.AddModelError("title", "主题为空。");
            }

            if (content.Length > 4000)
            {
                ModelState.AddModelError("content", "内容最大长度4000。");
            }

            if (title.Length > 1000)
            {
                ModelState.AddModelError("title", "主题最大长度1000。");
            }

            Shop shopInfo = this.UserSession.GetShop();
            if (null == shopInfo)
            {
                throw new Exception("用户店铺不存在.");
            }
            if (!ModelState.IsValid)
            {
                return View(ShopArticleService.GetShopArticleList(1, 10, shopInfo.ID));
            }
            ShopArticle data = new ShopArticle()
                {
                    Content = content,
                    Title = title,
                    ShopID = shopInfo.ID
                };
            try
            {
                ShopArticleService.AddShopArticle(data);
                return RedirectToAction("ShopNotice");
            }
            catch (Exception e)
            {
                ModelState.AddModelError("Error", e.Message);
            }
            return View(ShopArticleService.GetShopArticleList(1, 10, shopInfo.ID));
        }
        #endregion

        #region 代理
        [HttpGet]
        public ActionResult SetAgents()
        {
            var selAgentsShippedShop = ShopService.GetAgentsInfo(UserSession.UserID);
            if (null == selAgentsShippedShop)
            {
                selAgentsShippedShop = new AgentsInfo();
            }
            ViewData["selAgentsShippedShop"] = selAgentsShippedShop.ShippedShops;
            return View(ShopService.GetShopList(EShopType.ShippedShop, 1, ShopService.GetShopCount(EShopType.ShippedShop), null));
        }

        [HttpPost]
        public ActionResult SetAgents(long[] agents, long primaryAgent)
        {
            AgentsInfo info = new AgentsInfo();
            info.AgentsUserID = UserSession.UserID;
            info.ShippedShops = new List<AgentsShippedShop>();
            for (int i = 0; i < agents.Length; i++)
            {
                info.ShippedShops.Add(new AgentsShippedShop()
                {
                    AgentsUserID = UserSession.UserID,
                    ShippedShopID = agents[i],
                    IsDefault = agents[i] == primaryAgent
                });
            }
            try
            {
                ShopService.SetAgentsInfo(info);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            return RedirectToAction("SetAgents");
        }

        /// <summary>
        /// 关注商品
        /// </summary>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public ActionResult ConcernGoods(int? pageindex, int[] accesstype, string orderby)
        {
            int pageIndex = pageindex ?? 1;

            List<string> order = new List<string>();
            if (!string.IsNullOrEmpty(orderby))
            {
                order.Add(orderby);
            }
            List<EGoodsAccessType> goodsAccessType = new List<EGoodsAccessType>();
            if (null != accesstype && accesstype.Length > 0)
            {
                accesstype = accesstype.Distinct().ToArray();
                for (int i = 0; i < accesstype.Length; i++)
                {
                    goodsAccessType.Add((EGoodsAccessType)accesstype[i]);
                }
            }
            return View(GoodsService.GetGoodsAccessRecord(goodsAccessType, pageIndex, 20, order));
        }

        /// <summary>
        /// 订单管理
        /// </summary>
        /// <param name="pageindex"></param>
        /// <param name="orderby"></param>
        /// <returns></returns>
        public ActionResult OrderList(int? pageindex, int? pagesize, string order)
        {
            int index = pageindex ?? 1;
            int pageSize = pagesize ?? 20;
            return View(GoodsOrdersService.GetGoodsOrdersList(UserSession.UserID, index, pageSize, order));
        }
        #endregion

        #region 代发
        public ActionResult GiftList(int? pageindex, int? pagesize, string order)
        {
            int index = pageindex ?? 1;
            int pageSize = pagesize ?? 1; 
            return View(ShopGiftServices.GetShopGiftList(0, index, pageSize, order));
        }
        #endregion
    }
}
